import { useState, useEffect } from 'react';
import { Select } from 'antd';
import { getFormattedModels } from '../../api/model';
import { getFormattedMCPServers } from '../../api/mcp';
import { STORAGE_KEYS, getStorageItem, setStorageItem } from '../../utils/storage';

const { Option } = Select;

type SelectConfigureProps = {
  onProviderChange: (provider: string) => void;
  onModelChange: (model: string) => void;
  onMcpServerChange: (mcpServer: string) => void;
};

const SelectConfigure = ({ 
  onProviderChange,
  onModelChange, 
  onMcpServerChange 
}: SelectConfigureProps) => {
  // 仅保留渲染所需的本地状态
  const [providers, setProviders] = useState<Array<{value: string, label: string}>>([]);
  const [models, setModels] = useState<Array<{value: string, label: string}>>([]);
  const [mcpServers, setMcpServers] = useState<Array<{value: string, label: string}>>([]);
  const [cachedModelData, setCachedModelData] = useState<Record<string, string[]>>({});

  // 初始化供应商数据
  useEffect(() => {
    const loadModels = async () => {
      const { providers: formattedProviders, rawData } = await getFormattedModels();
      setProviders(formattedProviders);
      setCachedModelData(rawData);
      
      const cachedProvider = getStorageItem(STORAGE_KEYS.SELECTED_PROVIDER);
      if (cachedProvider) {
        handleProviderChange(cachedProvider);
      } else if (formattedProviders[0]) {
        handleProviderChange(formattedProviders[0].value);
      }
    };
    loadModels();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 初始化 MCP 服务数据
  useEffect(() => {
    const loadMCPServers = async () => {
      const formattedServers = await getFormattedMCPServers();
      setMcpServers(formattedServers);
      
      const cachedServer = getStorageItem(STORAGE_KEYS.SELECTED_MCP);
      if (cachedServer) {
        handleMcpServerChange(cachedServer);
      } else if (formattedServers[0]) {
        handleMcpServerChange(formattedServers[0].value);
      }
    };
    loadMCPServers();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 供应商变更处理（触发父组件回调）
  const handleProviderChange = (newProvider: string) => {
    setStorageItem(STORAGE_KEYS.SELECTED_PROVIDER, newProvider); // 保留存储逻辑
    onProviderChange(newProvider);  // 触发父组件回调
    
    const currentModels = cachedModelData[newProvider]?.map(model => ({
      value: model,
      label: model
    })) || [];
    setModels(currentModels);
    if (currentModels[0]) {
      handleModelChange(currentModels[0].value);
    }
  };

  // 模型变更处理（触发父组件回调）
  const handleModelChange = (newModel: string) => {
    setStorageItem(STORAGE_KEYS.SELECTED_MODEL, newModel); // 保留存储逻辑
    onModelChange(newModel);  // 触发父组件回调
  };

  // MCP 服务变更处理（触发父组件回调）
  const handleMcpServerChange = (newServer: string) => {
    setStorageItem(STORAGE_KEYS.SELECTED_MCP, newServer); // 保留存储逻辑
    onMcpServerChange(newServer);  // 触发父组件回调
  };

  return (
    <div className="model-configure-container">
      <div className="provider-select-container ">  
        <span className="provider-model-label">Provider</span>  
        <Select
          className="provider-select"
          onChange={handleProviderChange}
          placeholder="选择供应商"
          value={getStorageItem(STORAGE_KEYS.SELECTED_PROVIDER)} // 从存储读取当前值
        >
          {providers.map(p => (
            <Option key={p.value} value={p.value}>{p.label}</Option>
          ))}
        </Select>
      </div>
      <div className="model-select-container ">
        <span className="provider-model-label">Model</span>  
        <Select
          className="model-select"  
          onChange={handleModelChange}
          placeholder="选择模型"
          disabled={!models.length}
          value={getStorageItem(STORAGE_KEYS.SELECTED_MODEL)} // 从存储读取当前值
        >
          {models.map(m => (
            <Option key={m.value} value={m.value}>{m.label}</Option>
          ))}
        </Select>
      </div>
      <div className="mcpServer-select-container">
        <span className="mcpServer-label">MCP Server</span>
        <Select
          className="mcpServer-select"
          onChange={handleMcpServerChange}
          placeholder="选择MCP服务"
          value={getStorageItem(STORAGE_KEYS.SELECTED_MCP)} // 从存储读取当前值
        >
          {mcpServers.map(s => (
            <Option key={s.value} value={s.value}>{s.label}</Option>
          ))}
        </Select>
      </div>
    </div>
  );
};

export default SelectConfigure;